package com.cdu.xinmiao.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.cdu.xinmiao.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;

public class MissionActivity extends AppCompatActivity {
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 100;
    private TitleBar titleBar;
    private WebView webView;
    private SuperButton to_photo;
    private BottomNavigationView bottomNavigationView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_mission);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.mission), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getId();

        bindClick();

        requestLocationPermission();
    }

    private void getId() {
        titleBar = findViewById(R.id.titleBar_back);
        webView = findViewById(R.id.webView);

        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setSelectedItemId(R.id.item_mission);
        to_photo = findViewById(R.id.to_photo);
    }

    private void bindClick() {
        titleBar.setLeftClickListener(v -> finish());
        webView.setVisibility(View.VISIBLE);

        to_photo.setOnClickListener(v -> {
            Intent intent = new Intent(MissionActivity.this, DakaActivity.class);
            startActivity(intent);
        });

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.item_home:
                        Intent intent1 = new Intent(MissionActivity.this, HomeActivity.class);
                        startActivity(intent1);
                        break;
                    case R.id.item_user:
                        Intent intent2 = new Intent(MissionActivity.this, UserActivity.class);
                        startActivity(intent2);
                        break;
                    case R.id.item_mission:
                        break;
                    case R.id.item_rank:
                        Intent intent4 = new Intent(MissionActivity.this, RankActivity.class);
                        startActivity(intent4);
                        break;
                }
                return false;
            }
        });
    }

    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            // 如果已经有权限了，直接显示WebView
            showWebView();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了地理位置权限，显示WebView
                showWebView();
            } else {
                // 用户拒绝了地理位置权限，可以给出提示或者其他处理
            }
        }
    }

    private void showWebView() {
        String url = "https://ditu.baidu.com/";
        String destinationAddress = "成都大学男生宿舍-16栋";
        webView.getSettings().setJavaScriptEnabled(true); // 启用 JavaScript
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 注入目的地地址
                String javascript = "javascript:(function() { " +
                        "var map = new BMap.Map('container'); " +
                        "var myGeo = new BMap.Geocoder(); " +
                        "myGeo.getPoint('" + destinationAddress + "', function(point) { " +
                        "if (point) { " +
                        "map.centerAndZoom(point, 16); " +
                        "map.addOverlay(new BMap.Marker(point)); " +
                        "} else { " +
                        "alert('无法找到该地址！'); " +
                        "}" +
                        "});" +
                        "})()";
                webView.evaluateJavascript(javascript, null);
            }
        });
        webView.setWebViewClient(new WebViewClient()); // 设置 WebViewClient 以在 WebView 内加载网页
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setDomStorageEnabled(true); // 开启本地DOM存储
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

        });
        webView.loadUrl(url);
    }
}